<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { ElTable, FormInstance, ElMessage, type FormRules } from "element-plus"
import { getUserDataApi } from "@/api/user"
// 接口
import { getyunuser, banUser, bandingUser, exportExcelList, getyunuserAll } from "@/api/yunShang"
import { usePagination } from "@/hooks/usePagination"
import { Download } from "@element-plus/icons-vue"
const loading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// #endregion

// #region 查
const tableTotal = ref<number>()
const tableData = ref<any>([])
const tableData1 = ref<any>([])

// #region 分销账号
const getyunuserData = () => {
  loading.value = true
  getyunuser({
    page: paginationData.currentPage,
    size: paginationData.pageSize
  })
    .then((res: any) => {
      tableData.value = res.data.list
      tableTotal.value = res.data.total
      // console.log(res)
    })
    .finally(() => {
      loading.value = false
    })
}
getyunuserAll()
  .then((res: any) => {
    tableData1.value = res.data
  })
  .finally(() => {
    loading.value = false
  })
// #endregion
//是否禁用账号
const isBan = (row: any) => {
  // console.log(row)
  banUser({ userId: row.user_id, isBan: row.ban }).then((res: any) => {
    if (res.code == 200) {
      getyunuserData()
    } else {
      row.ban = false
    }
    ElMessage.success(res.message)
  })
}
// #region 绑定凡思特账号
const dialogVisible = ref<boolean>(false)
const formData = reactive<any>({
  userId: "", // id
  dcUserId: "" // 凡思特账户id
})
const comboList = ref<any>([])
getUserDataApi({
  page: 1,
  size: 100000,
  name: undefined,
  role: "",
  department: "",
  team: ""
}).then((res) => {
  comboList.value = res.data.userList
  // console.log(res, "用户数据")
})

const handleUpdate = (row: any) => {
  // console.log(row, 7777777)
  dialogVisible.value = true
  formData.userId = row.user_id
  formData.dcUserId = row.dc_user_id
}
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      bandingUser({
        userId: formData.userId,
        dcUserId: formData.dcUserId
      }).then(() => {
        ElMessage.success("修改成功")
        // console.log("修改")
        dialogVisible.value = false
        getyunuserData()
      })
    }
  })
}
const formRef = ref<FormInstance | null>(null)
const formRules: FormRules = reactive({
  dcUserId: [{ required: true, trigger: "change", message: "请选择账号" }]
})
const clearValidateA = () => {
  formRef.value?.clearValidate()
  formRef.value?.resetFields()
}
const resetForm = () => {
  clearValidateA()
  // 清空reactive对象里面的key值
  Object.keys(formData).map((key) => {
    delete formData[key]
  })
}
const formatterCombo = (row: any, column: any, celValue: any) => {
  comboList.value.filter((item: any) => {
    // console.log(item, "过滤")
    if (item.id == row.dc_user_id) {
      celValue = item.name
    }
  })
  return celValue
}
// #endregion
//导出代理列表
const exportExcel = async () => {
  loading.value = true
  await exportExcelList({})
    .then((res: any) => {
      const blob = new Blob([res.data], {
        type: "application/xlsx;charset=utf-8"
      })
      const downloadElement = document.createElement("a")
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = "云尚代理列表.xlsx"
      document.body.appendChild(downloadElement)
      downloadElement.click()
      window.URL.revokeObjectURL(href)
    })
    .finally(() => {
      loading.value = false
    })
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getyunuserData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-button type="primary" :icon="Download" @click="exportExcel">导出Excel</el-button>
    </el-card>

    <!-- 中间部分 -->
    <el-card shadow="never" v-loading="loading">
      <!-- 顶部添加职位 -->
      <div class="middle-top">
        <!-- <div>
          <el-button type="primary" @click="dialogVisible = true">添加团队</el-button>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="downLoad" />
          </el-tooltip>
        </div> -->
      </div>
      <!-- 中间渲染内容 -->
      <div class="table-center">
        <el-table :data="tableData">
          <el-table-column prop="user_id" label="ID" width="120" align="center" />
          <el-table-column prop="user_name" label="代理账号" align="center" />
          <el-table-column prop="allBalance" label="历史总余额" align="center" />
          <el-table-column prop="user_balance" label="可提现余额" align="center" />
          <!-- <el-table-column prop="user_mobile" label="手机号" align="center" /> -->
          <el-table-column
            prop="dc_user_id"
            label="凡思特账号"
            align="center"
            :formatter="formatterCombo"
            show-overflow-tooltip
          />
          <el-table-column prop="balance" label="上级代理" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.user_super" clearable filterable placeholder="请选择分销账号" disabled>
                <el-option
                  v-for="item in tableData1"
                  :key="item.user_id"
                  :label="item.user_name"
                  :value="item.user_id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="是否禁用" width="150" align="center">
            <template #default="scope">
              <!-- <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button> -->
              <el-switch
                v-model="scope.row.ban"
                inline-prompt
                active-text="是"
                inactive-text="否"
                @click="isBan(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="绑定账号" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" title="修改" @close="resetForm" width="38%">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
        :inline="true"
      >
        <el-form-item prop="dcUserId" label="账号名">
          <el-select v-model="formData.dcUserId" filterable clearable placeholder="请选套餐">
            <el-option v-for="item in comboList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// .box-card {
//   height: 70px;
//   margin-bottom: 20px;
// }
.search-wrapper {
  margin-bottom: 20px;
}
.middle-top {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
